<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="userDialogFormRef" :model="state" :rules="state.rules" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="账户名称" prop="ruleForm.userName">
							<el-input v-model="state.ruleForm.userName" placeholder="请输入账户名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="登录名" prop="ruleForm.loginName">
							<el-input v-model="state.ruleForm.loginName" placeholder="请输入登录名" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户昵称">
							<el-input v-model="state.ruleForm.userNickName" placeholder="请输入用户昵称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户描述">
							<el-input v-model="state.ruleForm.userDescribe" placeholder="请输入用户描述"
								maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户性别" prop="ruleForm.userSex">
							<el-radio-group v-model="state.ruleForm.userSex">
								<el-radio label="1">男</el-radio>
								<el-radio label="0">女</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否启用" prop="ruleForm.userStatus">
							<el-radio-group v-model="state.ruleForm.userStatus">
								<el-radio label="1">启用</el-radio>
								<el-radio label="0">不启用</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="默认角色" prop="ruleForm.defaultRoleId">
							<el-select v-model="state.ruleForm.defaultRoleId" placeholder="请选择" clearable class="w100">
								<el-option v-for="item in defaultRoleOptions" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="默认部门" prop="ruleForm.defaultDeptId">
							<el-select v-model="state.ruleForm.defaultDeptId" placeholder="请选择" clearable class="w100">
								<el-option v-for="item in defaultDeptOptions" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="关联角色" prop="ruleForm.roleList">
							<el-select v-model="state.ruleForm.roleList" multiple filterable :reserve-keyword="false"
								remote placeholder="可输入关键字新增" :remote-method="getRole" :loading="roleLoading" @change="roleChange">
								<el-option v-for="item in roleOptions" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="所属部门" prop="ruleForm.deptList">
							<el-select v-model="state.ruleForm.deptList" multiple filterable :reserve-keyword="false"
								remote placeholder="可输入关键字新增" :remote-method="getDept" :loading="deptLoading" @change="deptChange">
								<el-option v-for="item in deptOptions" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>

				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(userDialogFormRef)" size="default">{{ state.dialog.submitTxt
					}}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus'
import { userApi } from './api';
import { ElMessage } from 'element-plus';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
// 引入 api 请求接口
const api = userApi();
const deptLoading = ref(false);
const roleLoading = ref(false);
interface ListItem {
	value: string
	label: string
}
const defaultDeptOptions = ref<ListItem[]>([]);
const defaultRoleOptions = ref<ListItem[]>([]);
const deptOptions = ref<ListItem[]>([]);
const roleOptions = ref<ListItem[]>([]);
// 定义变量内容
const userDialogFormRef = ref();
const state = reactive({
	ruleForm: {
		id: '',//主键id
		userName: '', // 用户名
		userNickName: '', // 用户昵称
		loginName: '', // 登录名
		userSex: '', // 性别 0-女 1-男
		userStatus: '1', // 用户状态  0-禁用 1-启用
		userDescribe: '', // 用户描述
		defaultRoleId: '', // 默认角色id
		defaultRoleName: '', // 默认角色名称
		defaultDeptId: '', // 默认部门id
		defaultDeptName: '', // 默认部门名称
		roleList: [] as string[], // 关联角色id集合
		deptList: [] as string[], // 所属部门id集合
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	rules: {
		'ruleForm.userName': { required: true, message: '请输入用户名', trigger: 'blur' },
		'ruleForm.loginName': { required: true, message: '请输入登录名', trigger: 'blur' },
		'ruleForm.userSex': { required: true, message: '请选择用户性别', trigger: 'blur' },
		'ruleForm.defaultRoleId': { required: true, message: '请选择默认角色', trigger: 'blur' },
		'ruleForm.defaultDeptId': { required: true, message: '请选择默认部门', trigger: 'blur' },
		'ruleForm.roleList': { required: true, message: '请选择关联角色', trigger: 'blur' },
		'ruleForm.deptList': { required: true, message: '请选择关联部门', trigger: 'blur' },
	},
});


// 打开弹窗
const openDialog = (type: string, row: any) => {
	if (type === 'edit') {
		state.ruleForm = row;
		state.dialog.title = '修改用户';
		state.dialog.submitTxt = '修 改';
		//从后台获取该菜单的所有上级菜单，用于回显
		api.getUserRoleAndDeptInfo({'id':row.id}).then(
			function (res) {
				const data = res.data;
				defaultDeptOptions.value = data.deptList.map((item: any) => {
					return { value: `${item.id}`, label: `${item.deptName}` }
				});
				deptOptions.value = defaultDeptOptions.value;
				state.ruleForm.deptList = data.deptList.map((item: any) => {
					return item.id
				});
				defaultRoleOptions.value = data.roleList.map((item: any) => {
					return { value: `${item.id}`, label: `${item.roleName}` }
				})
				roleOptions.value = defaultRoleOptions.value;
				state.ruleForm.roleList = data.roleList.map((item: any) => {
					return item.id
				});
			}
		)
	} else {
		//新增时 主键id置为空
		state.ruleForm.id = '';
		state.dialog.title = '新增用户';
		state.dialog.submitTxt = '新 增';
	}
	state.dialog.isShowDialog = true;

};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid) => {
		if (valid) {
			// console.log('校验通过！')
			api.save(state.ruleForm).then(
				(res) => {
					if (res.data.code === "000000") {
						ElMessage.success(res.data.message);
						closeDialog(); // 关闭弹窗
						emit('refresh');
					} else {
						ElMessage.warning(res.data.message);
					}
				}
			)
		} else {
			// console.log('校验未通过！')
			return false
		}
	})
};
const deptChange = (val:any) => {
	if (Object.keys(val).length !== 0) {
		const valStr = val.join();
		//关联部门不包含已选择的默认部门，则默认部门置为空
		if(!valStr.includes(state.ruleForm.defaultDeptId)){
			state.ruleForm.defaultDeptId = '';
		}
		//通过id集合字符串去后台查询名称
		api.getDeptByIds({ "idsStr":  valStr}).then(
			function (res) {
				const data = res.data;
				defaultDeptOptions.value = data.map((item: any) => {
					return { value: `${item.id}`, label: `${item.deptName}` }
				})
			}
		)
	} else {
		defaultDeptOptions.value = [];
		state.ruleForm.defaultDeptId = '';
	}
}

//远程查询部门信息
const getDept = (query: string) => {
	if (query) {
		deptLoading.value = true
		api.getDeptList({ "deptName": query }).then(
			function (res) {
				const data = res.data;
				deptOptions.value = data.map((item: any) => {
					return { value: `${item.id}`, label: `${item.deptName}` }
				})
				deptLoading.value = false
			}
		)
	} else {
		deptOptions.value = []
	}
}

//关联角色改变事件
const roleChange = (val:any) => {
	if (Object.keys(val).length !== 0) {
		const valStr = val.join();
		//关联角色不包含已选择的默认角色，则默认角色置为空
		if(!valStr.includes(state.ruleForm.defaultRoleId)){
			state.ruleForm.defaultRoleId = '';
		}
		//通过id集合字符串去后台查询名称
		api.getRoleByIds({ "idsStr":  valStr}).then(
			function (res) {
				const data = res.data;
				defaultRoleOptions.value = data.map((item: any) => {
					return { value: `${item.id}`, label: `${item.roleName}` }
				})
			}
		)
	} else {
		defaultRoleOptions.value = [];
		state.ruleForm.defaultDeptId = '';
	}
}

//远程查询角色信息
const getRole = (query: string) => {
	if (query) {
		roleLoading.value = true
		api.getRoleList({ "roleName": query }).then(
			function (res) {
				const data = res.data;
				roleOptions.value = data.map((item: any) => {
					return { value: `${item.id}`, label: `${item.roleName}` }
				})
				roleLoading.value = false
			}
		)
	} else {
		roleOptions.value = []
	}
}
// 暴露变量
defineExpose({
	openDialog,
});
</script>
